from flask import Flask, render_template, request, redirect, url_for, session, jsonify
import sqlite3
import os
from datetime import datetime

app = Flask(__name__)
app.secret_key = 'campus_food_secret_key_2024'

# 数据库连接函数
def get_db_connection():
    conn = sqlite3.connect('campus_food.db')
    conn.row_factory = sqlite3.Row
    return conn

# 首页
@app.route('/')
def index():
    conn = get_db_connection()
    canteens = conn.execute('SELECT * FROM canteens ORDER BY score DESC').fetchall()
    locations = conn.execute('SELECT DISTINCT location FROM canteens').fetchall()
    conn.close()
    
    return render_template('index.html', canteens=canteens, locations=locations)

# 详情页
@app.route('/detail/<int:canteen_id>')
def detail(canteen_id):
    conn = get_db_connection()
    canteen = conn.execute('SELECT * FROM canteens WHERE id = ?', (canteen_id,)).fetchone()
    reviews = conn.execute('''
        SELECT r.*, u.username FROM reviews r 
        JOIN users u ON r.user_id = u.id 
        WHERE r.canteen_id = ? 
        ORDER BY r.created_at DESC
    ''', (canteen_id,)).fetchall()
    conn.close()
    
    return render_template('detail.html', canteen=canteen, reviews=reviews)

# 登录页
@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']
        
        conn = get_db_connection()
        user = conn.execute(
            'SELECT * FROM users WHERE username = ? AND password = ?',
            (username, password)
        ).fetchone()
        conn.close()
        
        if user:
            session['username'] = username
            session['user_id'] = user['id']
            return redirect(url_for('index'))
        else:
            return render_template('login.html', error='用户名或密码错误')
    
    return render_template('login.html')

# 注册页
@app.route('/register', methods=['GET', 'POST'])
def register():
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']
        confirm_password = request.form['confirm_password']
        
        if password != confirm_password:
            return render_template('register.html', error='两次密码输入不一致')
        
        conn = get_db_connection()
        try:
            conn.execute(
                'INSERT INTO users (username, password) VALUES (?, ?)',
                (username, password)
            )
            conn.commit()
            return redirect(url_for('login'))
        except sqlite3.IntegrityError:
            return render_template('register.html', error='用户名已存在')
        finally:
            conn.close()
    
    return render_template('register.html')

# 退出登录
@app.route('/logout')
def logout():
    session.clear()
    return redirect(url_for('index'))

# 提交评价
@app.route('/submit_review', methods=['POST'])
def submit_review():
    if 'username' not in session:
        return jsonify({'success': False, 'message': '请先登录'})
    
    canteen_id = request.form['canteen_id']
    rating = request.form['rating']
    content = request.form['content']
    
    conn = get_db_connection()
    user = conn.execute(
        'SELECT id FROM users WHERE username = ?', (session['username'],)
    ).fetchone()
    
    if user:
        conn.execute('''
            INSERT INTO reviews (user_id, canteen_id, rating, content, created_at)
            VALUES (?, ?, ?, ?, ?)
        ''', (user['id'], canteen_id, rating, content, datetime.now()))
        conn.commit()
        conn.close()
        return jsonify({'success': True, 'message': '评价提交成功'})
    
    conn.close()
    return jsonify({'success': False, 'message': '提交失败'})

if __name__ == '__main__':
    # 检查数据库是否存在，不存在则初始化
    if not os.path.exists('campus_food.db'):
        print("正在初始化数据库...")
        import init_db
        print("数据库初始化完成！")
    
    print("=" * 50)
    print("校园美食查询系统启动成功！")
    print("访问地址: http://localhost:5000")
    print("按 Ctrl+C 停止服务器")
    print("=" * 50)
    
    app.run(debug=True, host='0.0.0.0', port=5000)